package cn.szzsi.business.interceptor;

import cn.szzsi.AConfig;
import cn.szzsi.common.bean.WeixinConfig;
import cn.szzsi.common.util.CommonUtil;
import cn.szzsi.model.SiteConfig;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.*;
import com.jfinal.weixin.sdk.api.JsTicketApi.JsApiType;

import java.util.ArrayList;
import java.util.Collections;
import java.util.UUID;

/**
 * @author Javen
 * 2016年5月13日
 */
public class CardJssdkInterceptor   implements Interceptor {
    /**
     * 如果要支持多公众账号，只需要在此返回各个公众号对应的 ApiConfig 对象即可 可以通过在请求 url 中挂参数来动态从数据库中获取
     * ApiConfig 属性值
     */
    public ApiConfig getApiConfig() {
        ApiConfig ac = new ApiConfig();

        // 配置微信 API 相关常量
        //ac.setToken("ZtdTYB");
        ac.setAppId("wxc670e094b0aa0b5d");
        ac.setAppSecret("83182248c62d82dfd1080c1b450f67d1");

        /**
         * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
         * 2：false采用明文模式，同时也支持混合模式
         */
        ac.setEncryptMessage(AConfig.p.getBoolean("encryptMessage", false));
        ac.setEncodingAesKey(AConfig.p.get("encodingAesKey", "setting it in config file"));
        return ac;
    }
    public ApiConfig getApiConfig(WeixinConfig weixinConfig) {
        ApiConfig ac = new ApiConfig();
        // 配置微信 API 相关常量
        //ac.setToken(AConfig.p.get("token"));
        ac.setAppId(weixinConfig.getAppid());
        ac.setAppSecret(weixinConfig.getSecret());
        /**
         * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
         * 2：false采用明文模式，同时也支持混合模式
         */
        ac.setEncryptMessage(AConfig.p.getBoolean("encryptMessage", false));
        ac.setEncodingAesKey(AConfig.p.get("encodingAesKey", "setting it in config file"));
        return ac;
    }

    public void intercept(Invocation inv) {
        inv.invoke();
        Controller controller = inv.getController();
        String shopId=controller.getPara("shopId");
        SiteConfig siteConfig = null;
        if(StrKit.notBlank(shopId)){
            siteConfig = SiteConfig.getByShopId(shopId);
            WeixinConfig weixinConfig=new WeixinConfig();
            weixinConfig.setAppid(siteConfig.getStr("appid"));
            weixinConfig.setSecret(siteConfig.getStr("secret"));
            ApiConfigKit.setThreadLocalApiConfig(getApiConfig(weixinConfig));
        }else{
            ApiConfigKit.setThreadLocalApiConfig(getApiConfig());
        }
        JsTicket jsApiTicket = JsTicketApi.getTicket(JsApiType.jsapi);
        String jsapi_ticket = jsApiTicket.getTicket();
        String nonce_str = create_nonce_str();
        // 注意 URL 一定要动态获取，不能 hardcode.
        String url="";
        if(StrKit.notBlank(shopId)){
            url= CommonUtil.getBusinessWebName(siteConfig)+controller.getRequest().getServletPath();
        }else{
            url = "https://" + controller.getRequest().getServerName() // 服务器地址
                    + controller.getRequest().getContextPath() // 项目名称
                    + controller.getRequest().getServletPath();// 请求页面或其他地址
        }
        String qs = controller.getRequest().getQueryString(); // 参数
        if (qs != null) {
            url = url + "?" + (controller.getRequest().getQueryString());
        }
        String timestamp = create_timestamp();
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        //注意这里参数名必须全部小写，且必须有序
        String str = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;


        String signature = HashKit.sha1(str);
        controller.setAttr("appId", ApiConfigKit.getApiConfig().getAppId());
        controller.setAttr("nonceStr", nonce_str);
        controller.setAttr("timestamp", timestamp);
        controller.setAttr("url", url);
        controller.setAttr("signature", signature);
        controller.setAttr("jsapi_ticket", jsapi_ticket);
        controller.setAttr("base",controller.getRequest().getContextPath());
        controller.setAttr("weburl",CommonUtil.getBusinessWebName(siteConfig));
//		ApiConfigKit.getApiConfig().setToken("ZtdTYB");
        //String us = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=wx_card";
        //String result = HttpKit.post(String.format(us,AccessTokenApi.getAccessToken().getAccessToken()),"");
        String us = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+AccessTokenApi.getAccessToken().getAccessToken()+"&type=wx_card";
        String result = HttpKit.post(us,"");
        org.json.JSONObject userJson=new org.json.JSONObject(result);
        System.out.println("userJson------"+userJson);
        if (null != userJson) {
            if (0 != userJson.getInt("errcode")) {
                System.out.println("错误 errcode:"+userJson.getInt("errcode")+" errmsg:"+ userJson.getString("errmsg"));
            }else{
                String ticket = userJson.getString("ticket");
                String cardnonceStr=create_nonce_str();
                String cardtimestamp = create_timestamp();
                System.out.println("ticket:"+ticket);
                System.out.println("cardtimestamp:"+cardtimestamp);
                System.out.println("cardnonceStr:"+cardnonceStr);
//				String st2 = "12345"+time+ticket+noce_str+"oJTHKwLtVnD3FoYSNTv4PoHxMTGA"+"pJTHKwGvVFevzwal5WMUtk4wFxUI";

                ArrayList<String> list = new ArrayList<String>();
                list.add(cardtimestamp);
                list.add(cardnonceStr);
                list.add(ticket);
                list.add("pJTHKwMmEyXZqut8OQibz5LzLMno");

                Collections.sort(list);
                String st2 = "";
                for(String s:list){
                    st2 += s;
                }

                String cardsignature = HashKit.sha1(st2);
                System.out.println("cardsignature:"+cardsignature);

                controller.setAttr("cardsignature",cardsignature);
                controller.setAttr("cardnonceStr",cardnonceStr);
                controller.setAttr("cardtimestamp",cardtimestamp);
                controller.setAttr("cardId","pJTHKwMmEyXZqut8OQibz5LzLMno");
            }

        }
        //ApiConfigKit.getApiConfig().getToken();
    }



    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }



}
